package com.caohx.bms.service;

import com.caohx.bms.pojo.Book;
import com.caohx.bms.pojo.BookCategory;
import com.caohx.bms.repository.BookRepository;
import com.caohx.bms.repository.BookCategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private BookCategoryRepository bookCategoryRepository;

    // 添加图书
    public Book add(Book book, Long categoryId) {
        if (book.getId() != null) {
            throw new IllegalArgumentException("新增操作时，图书ID必须为空");
        }
        // 根据 categoryId 查询 BookCategory
        BookCategory category = bookCategoryRepository.findById(categoryId)
                .orElseThrow(() -> new IllegalArgumentException("图书分类不存在"));
        book.setCategory(category);
        return bookRepository.save(book);
    }

    // 修改图书
    public Book edit(Book book, Long categoryId) {
        if (book.getId() == null) {
            throw new IllegalArgumentException("图书ID不能为空");
        }
        // 根据 categoryId 查询 BookCategory
        BookCategory category = bookCategoryRepository.findById(categoryId)
                .orElseThrow(() -> new IllegalArgumentException("图书分类不存在"));
        book.setCategory(category);
        return bookRepository.save(book);
    }

    // 删除图书
    public void delete(Long id) {
        Book existingBook = bookRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在，参数异常！"));
        bookRepository.deleteById(id);
    }

    // 查询指定ID的图书
    public Book get(Long id) {
        return bookRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));
    }

    // 分页查询所有图书
    public Page<Book> listBooks(Pageable pageable) {
        return bookRepository.findAll(pageable);
    }
}
